package com.yutel.multher.reaper.task;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yutel.multher.reaper.ReaperServer;
import com.yutel.multher.reaper.domain.QueueList;
import com.yutel.multher.reaper.domain.TaskData;
import com.yutel.multher.reaper.listener.OnDataListener;

public class QueueTask<T extends TaskData> implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(QueueTask.class);
	private int oldCount = 0;
	private int queueMin;
	private int queueInterval;
	private QueueList<T> queueList;
	private OnDataListener<T> dataListener;

	public QueueTask(ReaperServer<T> reaperServer) {
		queueMin = reaperServer.getQueueMin();
		queueInterval = reaperServer.getQueueInterval();
		queueList = reaperServer.getQueueList();
		dataListener = reaperServer.getOnDataListener();
	}

	@Override
	public void run() {
		while (true) {
			try {
				int newCount = queueList.size();
				if (newCount > queueMin) {
					log.debug("task sleep time:{}", queueInterval);
					Thread.sleep(queueInterval);
				} else {
					if (oldCount == 0 && newCount == 0) {
						log.debug("task sleep time:{}", queueInterval);
						Thread.sleep(queueInterval);
					}
					List<T> list = dataListener.OnDataLoad(queueMin);
					if (list.size() > 0) {
						queueList.addAll(list);
						log.info("queue load data:{}", list.size());
					}
				}
				oldCount = newCount;
			} catch (InterruptedException e) {
				log.error("server is shutdown", e);
				dataListener.OnDataEnd(queueList.getAll());
			} catch (Exception e) {
				log.error("queue thread error", e);
			}
		}
	}

}
